home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2000 April / Disc 1 / APC541.ISO / workshop / c / Tstack.h < prev   
Encoding:
C/C++ Source or Header  |  2000-02-12  |  1.6 KB  |  81 lines

  1. // **************************************************************
  2. // tstack.h
  3. // Example program for Simple C++
  4. //
  5. // (c) 2000 Emmenjay Consulting Pty Ltd                          
  6. //                                                               
  7. // History                                                       
  8. // 12/02/2000 MJS  Initial Coding.                                 
  9. //                                                               
  10. // **************************************************************
  11.  
  12. template <class T>
  13. class TStack {
  14. public:
  15.   TStack( int size=1000 );
  16.   ~TStack( void );
  17.   bool Push( T &val );
  18.   bool Pop( T &val );
  19. private:
  20.   T *buff;
  21.   int count;
  22.   int buffsize;
  23.   bool Expand( int size );
  24. };
  25.  
  26. template <class T>
  27. TStack<T>::TStack( int size )
  28. {
  29.   count = buffsize = 0;
  30.   buff = 0;
  31.   Expand( size );
  32. }
  33.  
  34. template <class T>
  35. TStack<T>::~TStack( void )
  36. {
  37.   delete [] buff;
  38. }
  39.  
  40. template <class T> 
  41. bool TStack<T>::Push( T& val )
  42. {
  43.   if (count==buffsize)
  44.     if (!Expand(2*buffsize))
  45.        return false;
  46.   buff[count++] = val;
  47.   return true;
  48. }
  49.  
  50. template <class T>
  51. bool TStack<T>::Pop( T &val )
  52. {
  53.   if (count) {
  54.     val = buff[--count];
  55.     return true;
  56.   } else {
  57.     return false;
  58.   }
  59. }
  60.  
  61. template <class T>
  62. bool TStack<T>::Expand(int size)
  63. {
  64.   int i;
  65.   T *tmp = (T *)new T [size];
  66.   if (!tmp)
  67.     return false;
  68.   if (count>size)
  69.     count = size;
  70.   if (buff) {
  71.     for (i=0; i<count; i++)
  72.       tmp[i] = buff[i];
  73.     delete [] buff;
  74.   }
  75.   buff = tmp;
  76.   buffsize = size;
  77.   return true;
  78. }
  79.  
  80.  
  81.